<template>
  <div>
    <span :class="['lock-icon', {'close-color ': isLock}]" :style="{zIndex: isLock? 9999: 100}">
      <span class="iconfont icon-suoding ft-size24" @click="unlockPage" v-if="isLock"></span>
      <span class="iconfont icon-jiesuo ft-size24" @click="lockPage" v-else></span>
    </span>
    <lock-modal ref="lockModal" :userInfo="userInfo" @colseLock="colseLock" />
  </div>

</template>

<script>
import LockModal from './lockModal.vue'
import { getLocalStorage } from '@/utils'
import dayjs from 'dayjs'
export default {
  components: { LockModal },
  data () {
    return {
      isLock: false,
      userInfo: {},
      lockTimer: null,
      lastOperateTime: dayjs(new Date()).valueOf(),
      outTime: 5
    }
  },
  methods: {
    unlockPage () {
      localStorage.setItem('unlocakPage', 1)
      this.$refs.lockModal.unlocakPage = true
    },
    lockPage () {
      this.isLock = true
      localStorage.setItem('lockModalVisible', 1)
      this.$refs.lockModal.open()
      clearInterval(this.lockTimer)
    },
    colseLock () {
      this.isLock = false
      this.lastOperateTime = dayjs(new Date()).valueOf()
      this.isTimeOut()
    },
    onLastOperateEvent () {
      window.onmousemove = () => {
        if (!this.isLock) {
          this.lastOperateTime = dayjs(new Date()).valueOf()
        } else {
          clearInterval(this.lockTimer)
        }
      }
    },
    isTimeOut () {
      // 使用定时器前清除定时器
      clearInterval(this.lockTimer)
      this.lockTimer = setInterval(() => {
        this.outTime = localStorage.getItem('autoScreenLockTime') ? Number(localStorage.getItem('autoScreenLockTime')) : -1
        if (this.outTime != -1) {
          // console.log(1111111);
          let nowTime = dayjs(new Date()).valueOf() // 获取当前时间 
          if (nowTime - this.lastOperateTime > 1000 * this.outTime * 60) {
            // 提示一下用户
            this.$message.warning(this.$t('layout.overTimeAutoLock'))
            // 这里要清除定时器，结束任务
            clearInterval(this.lockTimer)
            // 锁屏
            this.lockPage()
            console.log(this.outTime)
          }
        } else {
          clearInterval(this.lockTimer)
        }
      }, 1000)
    }
  },
  created () {
    this.userInfo = getLocalStorage('user') || {}
    this.isLock = localStorage.getItem('lockModalVisible') == 1
    this.outTime = localStorage.getItem('autoScreenLockTime') ? Number(localStorage.getItem('autoScreenLockTime')) : -1
  },
  mounted () {
    this.onLastOperateEvent()
    this.isTimeOut()
  }
}
</script>